<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片格式转换与批量处理</title>
    <style>
        body { font-family: "Microsoft YaHei", "微软雅黑", sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
        .container { background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); margin-bottom: 30px; }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 30px; }
        h2 { color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-top: 0; }
        label { display: block; margin-bottom: 8px; font-weight: bold; color: #555; }
        input[type="file"], input[type="text"], select {
            width: calc(100% - 24px); /* 减去padding和border */
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #bdc3c7;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 15px;
        }
        input[type="file"] { padding: 8px; } /* 微调文件输入框 */
        button {
            background-color: #3498db;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        button:hover { background-color: #2980b9; }
        .result-box {
            margin-top: 25px;
            padding: 20px;
            border: 1px solid #ecf0f1;
            border-radius: 5px;
            background-color: #fdfdfd;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
        }
        .result-box h3 { margin-top: 0; color: #34495e; }
        .result-box ul { list-style-type: none; padding-left: 0; }
        .result-box li {
            margin-bottom: 12px;
            padding: 10px;
            background-color: #f9f9f9;
            border-left: 3px solid #3498db;
            word-wrap: break-word;
        }
        .result-box li strong { color: #2c3e50; }
        .result-box a { color: #2980b9; text-decoration: none; font-weight: bold; }
        .result-box a:hover { text-decoration: underline; }
        .status-success { color: #27ae60; font-weight: bold; }
        .status-error { color: #c0392b; font-weight: bold; }
        .status-info { color: #2980b9; font-weight: bold; }
        .note { font-size: 0.9em; color: #7f8c8d; margin-top: 10px; }
    </style>
</head>
<body>

    <h1>图片格式转换与批量处理服务</h1>

    <!-- 单个图片上传与转换 -->
    <div class="container">
        <h2>单个图片上传与转换</h2>
        <form id="singleImageUploadForm" enctype="multipart/form-data">
            <div>
                <label for="singleFile">选择图片文件:</label>
                <input type="file" id="singleFile" name="file" accept="image/*" required>
            </div>
            <div>
                <label for="singleTargetFormat">转换为目标格式:</label>
                <select id="singleTargetFormat" name="targetFormat">
                    <option value="webp">WebP</option>
                    <option value="png">PNG</option>
                    <option value="jpg">JPG</option>
                    <option value="jpeg">JPEG</option>
                    <option value="gif">GIF</option>
                    <option value="bmp">BMP</option>
                </select>
            </div>
            <button type="submit">上传并转换单个图片</button>
        </form>
        <div id="singleResult" class="result-box" style="display:none;"></div>
    </div>

    <!-- 文件夹（批量图片）上传与转换 -->
    <div class="container">
        <h2>文件夹（批量图片）上传、转换并打包</h2>
        <form id="folderImageUploadForm" enctype="multipart/form-data">
            <div>
                <label for="folderFiles">选择图片文件夹 (将处理文件夹内所有图片):</label>
                <input type="file" id="folderFiles" name="files" webkitdirectory directory multiple required>
            </div>
            <div>
                <label for="folderTargetFormat">将所有图片转换为目标格式:</label>
                <select id="folderTargetFormat" name="targetFormat">
                    <option value="webp">WebP</option>
                    <option value="png">PNG</option>
                    <option value="jpg">JPG</option>
                    <option value="jpeg">JPEG</option>
                    <option value="gif">GIF</option>
                    <option value="bmp">BMP</option>
                </select>
            </div>
            <div>
                <label for="outputSubfolder">输出子文件夹名称 (可选, 用于归类):</label>
                <input type="text" id="outputSubfolder" name="outputSubfolder" placeholder="例如：我的活动照片_转换后">
            </div>
            <button type="submit">上传、转换并打包文件夹</button>
        </form>
        <div id="folderResult" class="result-box" style="display:none;">
             <p class="note">注意：生成的下载链接（包括ZIP包）将在约 <strong>10 分钟</strong> 后失效并自动删除文件。</p>
        </div>
    </div>

<script>
    const API_BASE_URL = "http://localhost:8080/img"; // 请根据您的后端应用上下文路径调整

    // --- 单个图片上传处理器 ---
    document.getElementById('singleImageUploadForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = new FormData(this);
        const resultDiv = document.getElementById('singleResult');
        resultDiv.style.display = 'block';
        resultDiv.innerHTML = '<p class="status-info">正在上传并转换单个图片...</p>';

        try {
            const response = await fetch(`${API_BASE_URL}/upload-convert`, {
                method: 'POST',
                body: formData,
            });

            const data = await response.json(); // 假设后端返回 { code, message, data }

            if (response.ok && data.code === 200) { // 请确认您的成功状态码
                let html = `<h3><span class="status-success">单个图片转换成功!</span></h3>`;
                html += `<ul>`;
                html += `<li><strong>原始文件名:</strong> ${data.data.originalFilename}</li>`;
                html += `<li><strong>转换后文件名:</strong> ${data.data.convertedFilename}</li>`;
                html += `<li><strong>目标格式:</strong> ${data.data.format}</li>`;
                html += `<li><strong>下载链接:</strong> <a href="${data.data.downloadUrl}" target="_blank" title="点击下载转换后的图片">${data.data.convertedFilename}</a></li>`;
                html += `</ul>`;
                html += `<p class="note">注意：此下载链接将在约 <strong>10 分钟</strong> 后失效。</p>`;
                resultDiv.innerHTML = html;
            } else {
                resultDiv.innerHTML = `<h3><span class="status-error">操作失败:</span></h3><p>${data.message || '未知的服务器错误'}</p>`;
                if (data.data && typeof data.data === 'object') { // 确保data.data是对象才尝试stringify
                     resultDiv.innerHTML += `<pre>${JSON.stringify(data.data, null, 2)}</pre>`;
                } else if (data.data) {
                    resultDiv.innerHTML += `<p>附加信息: ${data.data}</p>`;
                }
            }
        } catch (error) {
            console.error('单个图片上传错误:', error);
            resultDiv.innerHTML = `<h3><span class="status-error">客户端错误:</span></h3><p>无法连接到服务器或发生意外错误: ${error.message}</p>`;
        }
    });

    // --- 文件夹（批量图片）上传处理器 ---
    document.getElementById('folderImageUploadForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = new FormData(this);
        const resultDiv = document.getElementById('folderResult');
        resultDiv.style.display = 'block';
        // 保留已有的提示信息，并在前面添加处理状态
        const existingNote = resultDiv.querySelector('.note') ? resultDiv.querySelector('.note').outerHTML : '<p class="note">注意：生成的下载链接（包括ZIP包）将在约 <strong>10 分钟</strong> 后失效并自动删除文件。</p>';
        resultDiv.innerHTML = '<p class="status-info">正在上传、转换并打包文件夹中的图片...</p>' + existingNote;


        try {
            const response = await fetch(`${API_BASE_URL}/upload-convert-folder`, {
                method: 'POST',
                body: formData,
            });

            const data = await response.json(); // 假设 { code, message, data: { processedFiles, errors, zipDownloadUrl } }
            let currentHtmlContent = '<p class="status-info">正在上传、转换并打包文件夹中的图片...</p>' + existingNote;


            if (response.ok && (data.code === 200 || data.code === 201)) { // 允许的成功状态码
                let html = `<h3>文件夹处理结果:</h3>`;
                html += `<p class="status-info">${data.message}</p>`;

                if (data.data && data.data.zipDownloadUrl) {
                    html += `<h4><span class="status-success">所有转换后的图片已打包:</span></h4>`;
                    html += `<ul><li><strong>ZIP包下载链接:</strong> <a href="${data.data.zipDownloadUrl}" target="_blank" title="点击下载包含所有已转换图片的ZIP包">${data.data.zipDownloadUrl.substring(data.data.zipDownloadUrl.lastIndexOf('/') + 1)}</a></li></ul>`;
                }

                if (data.data && data.data.processedFiles && data.data.processedFiles.length > 0) {
                    html += '<h4>单个文件处理详情:</h4><ul>';
                    data.data.processedFiles.forEach(file => {
                        html += `<li>`;
                        html += `<strong>原始文件名:</strong> ${file.originalFilename} <br/>`;
                        if (file.status === "成功") {
                            html += `<strong>转换后文件名 (在ZIP包内):</strong> ${file.convertedFilename} <br/>`;
                            html += `<strong>状态:</strong> <span class="status-success">${file.status}</span>`;
                        } else {
                            html += `<strong>状态:</strong> <span class="status-error">${file.status}</span>`;
                        }
                        html += `</li>`;
                    });
                    html += '</ul>';
                }

                if (data.data && data.data.errors && data.data.errors.length > 0) {
                    html += '<h4>处理过程中的错误信息:</h4><ul>';
                    data.data.errors.forEach(err => {
                        html += `<li class="status-error">${err}</li>`;
                    });
                    html += '</ul>';
                }
                resultDiv.innerHTML = html + existingNote; // 确保提示信息始终可见

            } else {
                resultDiv.innerHTML = `<h3><span class="status-error">操作失败:</span></h3><p>${data.message || '未知的服务器错误'}</p>`  + existingNote;
                if (data.data && typeof data.data === 'object') {
                     resultDiv.innerHTML = `<h3><span class="status-error">操作失败:</span></h3><p>${data.message || '未知的服务器错误'}</p><pre>${JSON.stringify(data.data, null, 2)}</pre>` + existingNote;
                } else if (data.data) {
                     resultDiv.innerHTML = `<h3><span class="status-error">操作失败:</span></h3><p>${data.message || '未知的服务器错误'}</p><p>附加信息: ${data.data}</p>` + existingNote;
                }
            }
        } catch (error) {
            console.error('文件夹上传错误:', error);
            resultDiv.innerHTML = `<h3><span class="status-error">客户端错误:</span></h3><p>无法连接到服务器或发生意外错误: ${error.message}</p>` + existingNote;
        }
    });

</script>

</body>
</html>